/**
 * @author Casanova
 */
function GetTableAnswers(id)
{
	var url = '../Ajax/QuestionProcess.php?type=0&id=' + id;
	$(".tableBody").empty();
	$.getJSON(url, function(data) {
		if(data.length == 0)
		{
			$(".tableBody").append("<tr><td colspan='5'>No Items</td></tr>");
		}
		else
		{
			checkProcess.totalItems = data.length;
			checkProcess.checkAllItems = $("#checkAllItem")[0];
			for(i = 0 ; i < data.length; i++)
			{
				item = data[i];
				var tr = "<tr><td class='action'><input type='checkbox' onclick='checkProcess.checkItem(this.checked)' class='checkItems' name='checkItems" + i + "' value='" + item.Id + "'/></td>" +
							"<td>" + item.Id  + "</td>" + 
							"<td>" + item.Content + "</td>";
				if(item.IsCorrect == 0)
					tr = tr + "<td>No</td>";
				else
					tr = tr + "<td>Yes</td>";  
				tr = tr + "<td><a href='#' onclick='ShowAnswerPanel(" + item.Id + ")'>Edit</a></td></tr>";
				$(".tableBody").append(tr); 
			}
		}
	});
}

function ShowPopup(id)
{
	GetTableAnswers(id);
	var winl = (screen.width-720)/2;
	$('div.flash').css('visibility', 'hidden');
	$.blockUI({
		message: $('div.popupPanel'),
		css: {
			width: '720px',
			height: '420px',
			cursor: 'pointer',	
			'text-align':'left',
			top:"15%", 
			left:winl,
			position:'fixed',
			'border-color':'white',
			'background-image':'url(../images/popupPanel_bg.jpg)'
		}
	}); 
}

function ClosePopupPanel()
{
	$.unblockUI(); 
	$('div.flash').css('visibility', 'visible');
}

function ShowAnswerPanel(id)
{
	if(id == 0)
	{
		$("#hdAnswerId")[0].value = 0;
		$("#answerHeader")[0].innerHTML = "Add New Answer";
		$("#rbIncorrect")[0].checked = true;
		$("#tbContent")[0].value = "";
	}
	else
	{
		var url = '../Ajax/QuestionProcess.php?type=1&id=' + id;
		$.getJSON(url, function(data) {
			$("#hdAnswerId")[0].value = data.Id;
			$("#answerHeader")[0].innerHTML = "Edit Answer";
			if(data.IsCorrect == 1)
				$("#rbCorrect")[0].checked = true;
			else
				$("#rbIncorrect")[0].checked = true;
			$("#tbContent")[0].value = data.Content;
		});
	}
  	$('#answerPanel').fadeOut('fast', function() {
    	$('#editAnswerPanel').fadeIn('fast', function() {});
	});
}

function HideAnswerPanel()
{
	$('#editAnswerPanel').fadeOut('fast', function() {
    	$('#answerPanel').fadeIn('fast', function() {});
	});
}

function SaveAnswer()
{
	var content = $("#tbContent")[0].value;
	var correct = 0;
	var id = $("#hdAnswerId")[0].value;
	var questionId = $("#hdQuestionId")[0].value;
	if(content == "")
	{
		alert("You must input the content");
		return;
	}
	if($("#rbCorrect")[0].checked)
		correct = 1;
	if(id == 0)
	{
		var url = '../Ajax/QuestionProcess.php?type=2';
	}
	else
	{
		var url = '../Ajax/QuestionProcess.php?type=3&id=' + id;
	}
	$.getJSON(url,{ 'content':content, 'correct':correct, 'question':questionId }, function(data) {
		if(data.result == 0)
		{
			alert("Can not create or update this answer , please try later");
		}
		else
		{
			GetTableAnswers(questionId);
			HideAnswerPanel();
		}
	});
}

var checkProcess = {
	checkedItems: 0,
	totalItems:0,
	checkAllItems: null,
	
	checkItem: function(value)
	{
		if(value)
		{
			checkProcess.checkedItems++;
			checkProcess.checkAllItems.checked = checkProcess.totalItems == checkProcess.checkedItems;
		}
		else
		{
			checkProcess.checkedItems--;
			checkProcess.checkAllItems.checked = false;
		}
	},
	
	checkAll: function(value)
	{
		var items = $('.checkItems');
		for (i = 0; i < items.length; i++)
		{
			items[i].checked = value;
		}
		if(value)
		{
			checkProcess.checkedItems = items.length;
		}
		else
		{
			checkProcess.checkedItems = 0;
		}
	}
}

function SubmitSearchQuestion()
{
	category = $("#cbCategories")[0].value;
	url = document.forms[0].getAttribute("action");
	array = url.split("&");
	document.forms[0].setAttribute("action", array[0] + "&category=" + category);
	document.forms[0].submit();
}

function viewQuestionContent(id)
{
	var url = '../Ajax/QuestionProcess.php?type=5&id=' + id;
	$.getJSON(url, function(data) {
		$("#panelContent")[0].innerHTML = data.result;
		var winl = (screen.width-720)/2;
		$('div.flash').css('visibility', 'hidden');
		$.blockUI({
			message: $('div.popupPanel'),
			css: {
				width: '720px',
				height: '420px',
				cursor: 'pointer',	
				'text-align':'left',
				top:"15%", 
				left:winl,
				position:'fixed',
				'border-color':'white',
				'background-image':'url(../images/popupPanel_bg.jpg)'
			}
		}); 
	});
}

function categoryClick(check)
{
	if(check.checked)
	{
		$("#tbQuantity" + check.value)[0].disabled = false;
		$("#tbMarks" + check.value)[0].disabled = false;
	}
	else
	{
		$("#tbQuantity" + check.value)[0].disabled = true;
		$("#tbMarks" + check.value)[0].disabled = true;
	}
}

function checkvalidQuantity(tb)
{
	var regexCharNum = new RegExp('[0-9]');
	var kq = true;
	if(regexCharNum.test(tb.value))
	{
		if(isNaN(parseInt(tb.value)))
		{
			kq = false;
		}
		else
		{
			tb.value = parseInt(tb.value);
		}
	}
	else
	{
		kq = false;
	}
	if(!kq)
	{
		alert("You must input the number . Example : 10");
		tb.value = 0;
	}
}

function changeType()
{
	if($("#rbRandom")[0].checked)
	{
		$('#panelCustomQuestion').fadeOut('fast', function() {
    		$('#panelRandomQuestion').fadeIn('fast', function() {});
		});
	}
	else
	{
		$('#panelRandomQuestion').fadeOut('fast', function() {
    		$('#panelCustomQuestion').fadeIn('fast', function() {});
		});
	}
}

function checkvalidMarks(tb)
{
	var regexCharNum = new RegExp('[0-9].[0-9]|[0-9]');
	var kq = true;
	if(regexCharNum.test(tb.value))
	{
		if(isNaN(parseFloat(tb.value)))
		{
			kq = false;
		}
		else
		{
			tb.value = parseFloat(tb.value);
		}
	}
	else
	{
		kq = false;
	}
	if(!kq)
	{
		alert("You must input the decimal . Example : 0.5");
		tb.value = 0;
	}
}

function openCloseNode(a, ulId)
{
	if(a.getAttribute("class") == "expand")
	{
		a.setAttribute("class", "collapse");
	}
	else
	{
		a.setAttribute("class", "expand");
	}
	var ul = document.getElementById(ulId);
	$(ul).toggle("fast", function() {});
}

function selectedNode(lb, isUl)
{
	var hdSelectedCategory = document.getElementById("hdCurrentCategory");
	var hdPage = document.getElementById("hdCurrentPage");
	$(".lbNode").css("background-color", "white");
	$(".lbNode").css("color", "blue");
	$(lb).css("background-color", "blue");
	$(lb).css("color", "white");
	if(isUl)
	{
		hdSelectedCategory.value = lb.title;
		$("#tbMarksPerQuestion")[0].value = $("#hdMarksCategory" + lb.title)[0].value;
		$("#hdSelectedQuestion")[0].value = -1;
		pagingClick(1);
	}
	else
	{
		$("#hdSelectedQuestion")[0].value = lb.title;
	}
}

function SaveMarks()
{
	var hdSelectedCategory = document.getElementById("hdCurrentCategory");
	$("#hdMarksCategory" + hdSelectedCategory.value)[0].value = $("#tbMarksPerQuestion")[0].value;
	var hd = $("#hdMarksCategory" + hdSelectedCategory.value);
	for(ss = 0; ss < hd.length; ss++)
	{
		hd.value = $("#tbMarksPerQuestion")[0].value;
	}
	alert("Marks per question of this category has been changed");
}

function pagingClick(page)
{
	var hdSelectedCategory = document.getElementById("hdCurrentCategory");
	var hdPage = document.getElementById("hdCurrentPage");
	hdPage.value = page;
	var url = "../Ajax/TestProcess.php?type=0&page=" + hdPage.value +"&id=" + hdSelectedCategory.value;
	$("#tableQuestionsBody").empty();
	$.getJSON(url, function(data) {
		if(data.count == 0)
		{
			$("#tableQuestionsBody").append("<tr><td colspan='4'>No Items</td></tr>");
		}
		else
		{
			checkProcess.totalItems = data.count;
			checkProcess.checkAllItems = $("#checkAllItem")[0];
			$("#checkAllItem")[0].checked = false;
			for(i = 0 ; i < data.count; i++)
			{
				item = data.list[i];
				var tr = "<tr><td style='width:30px;' class='action'><input type='checkbox' onclick='checkProcess.checkItem(this.checked)' class='checkItems' name='checkItems" + i + "' value='" + item.Id + "'/></td>" +
							"<td style='width:100px;'>" + item.Id  + "</td>" + 
							"<td style='width:300px;'><a onclick=\"viewQuestionContent('" + item.Id + "')\">View Detail</a></td>";
				if(item.Sound == "")
					tr = tr + "<td style='width:70px;'>No</td>";
				else
					tr = tr + "<td style='width:70px;'>Yes</td>";  
				tr = tr + "</tr>";
				$("#tableQuestionsBody").append(tr); 
			}
			var pagingStr = "Page " + hdPage.value + " of " + data.totalPage + " ";
			var pageUrlFirst = "<a onclick=\"pagingClick('1')\">First</a>";
			var pageUrlLast = "<a onclick=\"pagingClick('" + data.totalPage + "')\">Last</a>";
			var pageUrlNext = "<a onclick=\"pagingClick('" + (parseInt(hdPage.value) + 1) + "')\">Next ></a>";
			var pageUrlPrev = "<a onclick=\"pagingClick('" + (parseInt(hdPage.value) - 1) + "')\">< Prev</a>";
			if(hdPage.value == 1)
			{
				pageUrlFirst = "First";
				pageUrlPrev = "< Prev";
			}
			if(hdPage.value >= data.totalPage)
			{
				pageUrlLast = "Last";
				pageUrlNext = "Next >";
			}
			$("#divPaging")[0].innerHTML = pagingStr + pageUrlFirst + " | " + pageUrlPrev + " | " + pageUrlNext + " | " + pageUrlLast;
		}
	});
	return false;
}

function CheckAvailableQuestion(id) // kiem tra 1 question da co trong category chua , co : true , ko co : false
{
	var questions = document.getElementsByName('hdQuestions');
	for(ii = 0; ii < questions.length; ii++)
	{
		if(questions[ii].value == id)
			return true;
	}
	return false;
}

function AddQuestion2Category()
{
	var checkItems = $('.checkItems');
	var currentCategory = $('#hdCurrentCategory')[0].value;
	var ulCategory = $('#ulCategory' + currentCategory)[0];
	var marks = $('#hdMarksCategory' + currentCategory)[0].value;
	for(i = 0; i < checkItems.length; i++)
	{
		if(checkItems[i].checked && !CheckAvailableQuestion(checkItems[i].value))
		{
			var stt = ulCategory.childNodes.length + 1;
			$(ulCategory).append("<li id='liQuestion" + checkItems[i].value + "'><img src='../images/star.png' onclick=\"viewQuestionContent('" + checkItems[i].value + "')\" /><label class='lbNode' title='"
			 + checkItems[i].value + "' onclick='selectedNode(this, false)'>Question id:" + checkItems[i].value
			 + "</label><input type='hidden' name='hdQuestions' value='" + checkItems[i].value + "' />"
			 + "<input type='hidden' id='hdMarksCategory" + currentCategory + "' name='hdQuestionMarks" + checkItems[i].value + "' value='" + marks + "' /></li>");
		}
	}
	CreateQuestionIdString();
}

function CreateQuestionIdString()
{
	var hdQuestions = document.getElementsByName("hdQuestions");
	var str = "";
	for(ww = 0; ww < hdQuestions.length; ww++)
	{
		str = str + hdQuestions[ww].value + ",";
	}
	if(hdQuestions.length > 0)
		$("#hdQuestionIds")[0].value = str.substring(0, str.length - 1);
}

function RemoveSelectedQuestion()
{
	var selectedIndex = $("#hdSelectedQuestion")[0].value;
	if(selectedIndex != -1)
	{
		var li = $("#liQuestion" + selectedIndex)[0];
		var parent = li.parentNode;
		parent.removeChild(li);
		$("#hdSelectedQuestion")[0].value = -1;
		CreateQuestionIdString();
	}
}

function RemoveAllQuestions()
{
	if (confirm("Do you want to remove all questions ?") == true) 
	{
		var uls = $('.ulCategories');
		for (ra = 0; ra < uls.length; ra++) {
			$(uls[ra]).empty();
		}
		CreateQuestionIdString();
	}
}
function registerProcess()
{
    if($("#txtUserName").val()!="" && $("#txtPassword").val()!=""  && $("#txtRetypePassword").val()!="" && $("#txtEmail").val()!="")
    {
        if($("#txtPassword").val()== $("#txtRetypePassword").val())
        {
            $.ajax(
            {
                url:"Register.php",
                data:"txtUserName=" + $("#txtUserName").val()+"&txtPassword=" +$("#txtPassword").val()+"&txtLastName=" + $("#txtLastName").val()+"&txtFirstName=" + $("#txtFirstName").val()+"&txtEmail=" + $("#txtEmail").val()+"&txtPhone=" + $("#txtPhone").val(),
                success:function(result)
                {
                    if(result==1)
                    {
                        alert("Register successfully !!!"); 
                   
                    }
                    else
                    {
                        alert("Register unsuccessfully !!!");
                    }
                
                }
            }
            );
            
            /*url = document.forms[0].getAttribute("action");

	        document.forms[0].setAttribute("action", url + "?txtUserName=" + $("#txtUserName").text()+"&txtPassword=" +$("#txtPassword").text()+"&txtLastName=" + $("#txtLastName").text()+"&txtFirstName=" + $("#txtFirstName").text()+"&txtEmail=" + $("#txtEmail").text());
	        document.forms[0].submit();
            */
            
        }
        else
        {
            alert("Passwords donot match !!!");
        }
    }
    else
    {
        alert("Must type require fields !!!");
    }
       
}

function refreshFields()
{
    $("#txtUserName").val("");
    $("#txtPassword").val("");
    $("#txtRetypePassword").val("");
    $("#txtLastName").val("");
    $("#txtFirstName").val("");
    $("#txtPhone").val("");
    $("#txtEmail").val("");
}